#pragma once
#include "Common.hpp"

class InetAddr{
public:
    InetAddr() {}

    InetAddr(struct sockaddr_in& addr)
    {
        SetAddr(addr);
    }

    InetAddr(uint16_t port, const std::string& ip)
        :_port(port), _ip(ip)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
    }

    InetAddr(uint16_t port)
        :_port(port)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        _addr.sin_addr.s_addr = INADDR_ANY;
    }

    ~InetAddr() {}

    void SetAddr(struct sockaddr_in& addr){
        _addr = addr;
        char ipbuffer[64];
        inet_ntop(AF_INET, &addr.sin_addr, ipbuffer, sizeof(ipbuffer));
        _ip = ipbuffer;
        _port = ntohs(addr.sin_port);
    }

    const struct sockaddr_in& NetAddr(){
        return _addr;
    }

    std::string StringAddr(){
        return _ip + ": " + std::to_string(_port);
    }

    socklen_t NetAddrLen(){
        return sizeof(_addr);
    }

    const struct sockaddr* NetAddrPtr(){
        return CONV(_addr);
    }

    bool operator== (const InetAddr& addr){
        return addr._ip == _ip && addr._port == _port;
    }

    std::string Ip(){
        return _ip;
    }

    uint16_t Port(){
        return _port;
    }

private:
    struct sockaddr_in _addr;
    uint16_t _port;
    std::string _ip;
};